<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import MenuApi from '@/api/menu'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag } from 'element-plus'
import { Icon } from '@/components/Icon'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()
const ids = ref<number[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await MenuApi.GetMenuList({
      ...unref(searchParams)
    })
    return {
      list: res.data || []
    }
  },
  fetchDelApi: async () => {
    const res = await MenuApi.DeletMenu(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const delLoading = ref(false)
const delData = async (row: any | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.menuId] : elTableExpose?.getSelectionRows().map((v: any) => v.menuId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    type: 'index'
  },
  {
    field: 'menuName',
    label: '菜单名称'
  },
  {
    field: 'status',
    label: '状态',
    slots: {
      default: (data: any) => {
        const status = data.row.status
        return (
          <>
            <ElTag type={status == '0' ? 'success' : 'danger'}>
              {status == '0' ? '正常' : '停用'}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'path',
    label: '路径'
  },
  {
    field: 'icon',
    label: '图标',
    slots: {
      default: (data: any) => {
        const icon = data.row?.icon
        if (icon) {
          return (
            <>
              <Icon icon={icon} />
            </>
          )
        } else {
          return null
        }
      }
    }
  },
  {
    field: 'action',
    width: '200px',
    label: '操作',
    slots: {
      default: (data) => {
        return (
          <>
            <span
              class="TableBtn"
              onClick={() =>
                action({ parentId: data.row.menuId, singlePage: data.row.singlePage }, 'add')
              }
            >
              {t('添加')}
            </span>
            <span class="TableBtn" onClick={() => action(data.row, 'edit')}>
              {t('修改')}
            </span>
            <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
              {t('删除')}
            </span>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'menuName',
    label: '菜单名称',
    component: 'Input',
    componentProps: {
      placeholder: '菜单名称'
    }
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      placeholder: '状态',
      options: [
        {
          value: '0',
          label: '正常'
        },
        {
          value: '1',
          label: '停用'
        }
      ]
    }
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? '修改' : '新增')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    saveLoading.value = true
    const res: any = ref(false)
    if (actionType.value == 'add') {
      res.value = await MenuApi.AddMenu(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      res.value = await MenuApi.EditMenu(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="12" />添加
      </BaseButton>
      <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    </div>
    <Table
      :columns="tableColumns"
      default-expand-all
      row-key="menuId"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
:deep(.el-table--default) {
  height: 485px !important;
}
</style>
